#include "mongoc_const.h"
#include "mongoc_data.h"

int write_grid(int cid, int nlon, int nlat, double lon[], double lat[]) {
  if (cid >= nbundle) {
    return FORTRAN_MONGO_NO_ERROR;
  }
  struct MongoObjectBundle *bundle = &bundles[cid];

  bson_error_t error;
  size_t ndoc = 100000;
  bson_t **docs = malloc(ndoc * sizeof(bson_t*));
  size_t l = 0, m = 0;

  for (int j = 0; j < nlat; ++j) {
    for (int i = 0; i < nlon; ++i) {
      docs[m] = BCON_NEW(
        "_id", BCON_INT32(l),
        "location", "{",
          "type", "Point",
          "coordinates", "[", BCON_DOUBLE(lon[i]), BCON_DOUBLE(lat[j]), "]",
        "}"
      );
      m++;
      if (m == ndoc) {
        printf("==> Insert %ld-%ld documents ...\n", l - ndoc + 1, l);
        if (!mongoc_collection_insert_many(bundle->col, docs, ndoc, NULL, NULL, &error)) {
          fprintf(stderr, "[Error]: Failed to insert data: %s\n", error.message);
          return EXIT_FAILURE;
        }
        for (m = 0; m < ndoc; ++m) {
          bson_destroy(docs[m]);
        }
        m = 0;
      }
      l++;
    }
  }
  printf("==> Insert %ld-%ld documents ...\n", l - m, l - 1);
  ndoc = m;
  if (!mongoc_collection_insert_many(bundle->col, docs, ndoc, NULL, NULL, &error)) {
    fprintf(stderr, "[Error]: Failed to insert data: %s\n", error.message);
    return EXIT_FAILURE;
  }
  for (m = 0; m < ndoc; ++m) {
    bson_destroy(docs[m]);
  }
  free(docs);

  return FORTRAN_MONGO_NO_ERROR;
}
